import 'dart:async';
import 'dart:io';

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:grab_the_order/app/data/services/permission_service.dart';
import 'package:grab_the_order/app/routes/app_pages.dart';

class SplashController extends GetxController {
  final permissionService = Get.find<PermissionService>();
  final box = GetStorage();
  Timer? _timer;

  final RxInt countdown = 3.obs;
  bool _isDialogShowing = false;

  // 【新增】控制“跳过”按钮是否显示的响应式变量
  final RxBool showSkipButton = false.obs;

  @override
  void onReady() {
    super.onReady();
    _checkAgreementStatusAndStart();
  }

  // 检查协议状态，并根据状态决定是否显示跳过按钮
  void _checkAgreementStatusAndStart() {
    bool hasAgreed = box.read('hasAgreedToTerms') ?? false;
    if (hasAgreed) {
      // 如果已经同意过协议，则显示跳过按钮
      showSkipButton.value = true;
    } else {
      // 如果没有同意过，则不显示
      showSkipButton.value = false;
    }
    // 无论如何都开始倒计时
    _startCountdown();
  }

  void _startCountdown() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value > 1) {
        countdown.value--;
      } else {
        _navigate();
        timer.cancel();
      }
    });
  }

  void skipCountdown() {
    _timer?.cancel();
    _navigate();
  }

  Future<void> _navigate() async {
    if (_isDialogShowing) return;

    bool hasAgreed = box.read('hasAgreedToTerms') ?? false;

    if (hasAgreed) {
      Get.offAllNamed(Routes.FRAMEWORK);
    } else {
      _isDialogShowing = true;
      bool? userAgreed = await permissionService.showPermissionDialog(
        title: '服务协议与隐私政策',
        content: '欢迎使用抢单助手！在使用前，请您仔细阅读并同意我们的服务协议和隐私政策。您的数据将受到严格保护。',
        confirmText: '同意并继续',
        cancelText: '不同意并退出',
      );
      _isDialogShowing = false;

      if (userAgreed == true) {
        await box.write('hasAgreedToTerms', true);
        Get.offAllNamed(Routes.FRAMEWORK);
      } else {
        exit(0);
      }
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }
}
